<template>
  <div>
    <!-- 派单完成 2018/3/7 11:44 zhangQ -->

    <Row>
      <i-col span="24">
        <Button type="error" size="large" @click="fleetDispatchDriverRemove">
          <Icon type="ios-download-outline"></Icon>
          撤销派单
        </Button>
        <Button type="primary" size="large" @click="addDriver" :disabled="addDriverBtnDisabled">
          <Icon type="ios-download-outline"></Icon>
          追加司机
        </Button>
      </i-col>
    </Row>
    <Row>
      <i-col span="24">
        <Table style="margin-top: 15px;" :columns="subOrderColumn" :data="rebuildData" @on-selection-change="subOrderCheck" height="600" highlight-row @on-current-change="onCurrentChange"></Table>
      </i-col>
    </Row>
    <xlinkModal v-model="operaModal.checkDriverShow" title="追加司机" className="vertical-center-modal" width="600px;">
      <checkDriverModal v-if="operaModal.checkDriverShow" :driverList="driverList" :form="currentRowDriversform" @dispatch="addDriverSave"></checkDriverModal>
    </xlinkModal>
  </div>
</template>

<script>
  import { assignmentForDriverRemoveKel, addDriverSave } from '@api/backEnd/mainOrder'
  import dispatchCompleteExpand from './dispatchCompleteExpand'
  import checkDriverModal from './checkDriverModal'
  import xlinkModal from '@components/modal/xlinkModal'
  import pinyin from '@components/common/pinyin'
  import _ from 'lodash'
  import { getTrainTypeCN } from './trainTypeEnum'

  export default {
    name: 'dispatch-complete',
    data () {
      let subOrderColumn = [
        {
          type: 'index',
          width: 60
        },
        {
          type: 'expand',
          width: 50,
          render: (h, params) => {
            console.log('params.row.expand', params.row.expand)
            return h(dispatchCompleteExpand, {
              props: {
                rows: params.row.expand
              }
            })
          }
        },
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '火车车种类型',
          ellipsis: 'false',
          width: 150,
          render: (h, params) => {
            let trainType = params.row.trainType
            let trainTypeCN = getTrainTypeCN(trainType)
            return (<span>{trainTypeCN}</span>)
          }
        },
        {
          title: '箱号',
          ellipsis: 'false',
          width: 150,
          key: 'containerNoBody',
          render: (h, params) => {
            let containerNo = params.row.containerNoHead + params.row.containerNoBody
            if (params.row.groupNo) {
              containerNo = '未指派司机子运单'
            }
            return (<span>{containerNo ? containerNo : ''}</span>)
          }
        },
        {
          title: '司机',
          ellipsis: 'false',
          key: 'driverId',
          width: 200,
          render: (h, params) => {
            return (<span>{params.row.driverName}</span>)
          }
        },
        {
          title: '送货地址',
          ellipsis: 'false',
          width: 200,
          key: 'shippingAddress',
          render: (h, params) => {
            return (<span>{params.row.shippingAddress}</span>)
          }
        },
        {
          title: '联系人',
          ellipsis: 'false',
          width: 100,
          key: 'contacts'
        },
        {
          title: '联系人电话',
          ellipsis: 'false',
          width: 150,
          key: 'contactsMobile'
        },
        {
          title: '发货人',
          ellipsis: 'false',
          key: 'zkfhrmc',
          width: 250
        },
        {
          title: '收货人',
          ellipsis: 'false',
          key: 'zkshrmc',
          width: 250
        },
        {
          title: '品名',
          ellipsis: 'false',
          key: 'zkpmhz0',
          width: 150
        },
        {
          title: '接取送达费(元)',
          ellipsis: 'false',
          key: 'zkjf018',
          width: 120
        },
        {
          title: '状态',
          ellipsis: 'false',
          width: 80,
          key: '',
          render: (h, params) => {
            let shippingAddress = params.row.shippingAddress
            if (shippingAddress) {
              return (<span style="color:green">已派单</span>)
            }
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: 250,
          render: (h, params) => {
            let voucherImg = params.row.voucherImg
            let viewImg = (<i-button size="small" style="margin-right: 5px;">图片查看</i-button>)
            if (voucherImg) {
              viewImg = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.viewDetailImgAction(params.row)}>图片查看</i-button>)
            }
            let btnArray = []
            powerUtil.contains('orderListUnfinishedFleet') && btnArray.push(viewImg)
            return (btnArray)
          }
        }
      ]
      let selectionSubOrder = []
      let rebuildData = []
      let currentRow = {}
      let addDriverBtnDisabled = true
      let operaModal = { checkDriverShow: false }
      let currentRowDriversform = {}
      let datas = { subOrderColumn, selectionSubOrder, rebuildData, currentRow, addDriverBtnDisabled, operaModal, currentRowDriversform }
      return datas
    },
    props: {
      dispatchCompleteData: {
        type: Array,
        default () {
          return []
        }
      },
      currentMainOrder: {
        type: Object,
        default () {
          return {}
        }
      },
      driverList: {
        type: Array,
        default () {
          return []
        }
      }
    },
    computed: {},
    watch: {
      'dispatchCompleteData.length' (val, oldval) {
        if (val > 0) {
          this.rebuildMethod()
        } else {
          this.rebuildData = []
        }
      }
    },
    methods: {
      viewDetailImgAction (row) {
        this.$emit('viewDetailImg', row)
      },
      subOrderCheck (selection) {
        this.selectionSubOrder = selection
      },
      fleetDispatchDriverRemove () {
        if (!(this.selectionSubOrder && this.selectionSubOrder.length > 0)) {
          this.$Notice.warning({
            title: '警告',
            desc: '请选择子运单'
          })
          return
        }
        let param = []
        this.selectionSubOrder.forEach((item) => {
          if (!item.groupNo) {
            param.push({ mainOrderNo: item.mainOrderNo, subOrderNo: item.orderNo, driverId: item.driverId, address: item.shippingAddress })
          } else if (item.groupNo) {
            let groupData = { groupNo: item.groupNo, mainOrderNo: item.expand[0].mainOrderNo, list: [], driverIds: item.expand[0].driverIds }
            item.expand.forEach((obj) => {
              groupData.list.push({ mainOrderNo: obj.mainOrderNo, subOrderNo: obj.orderNo, containerNoBody: obj.containerNoBody, containerNoHead: obj.containerNoHead })
            })
            param.push(groupData)
          }
        })
        assignmentForDriverRemoveKel(param).then(res => {
          if (+res.data.isSuccess === 1) {
            this.$Message.success('撤销成功')
            this.$emit('refreshSource')
          } else {
            this.$Message.success(res.data.res)
          }
        })
      },
      /**
       * TODO(重新构建数据)
       * @auther zhangQ
       * @date 2018/4/3 16:49
       */
      rebuildMethod () {
        let groupList = _.groupBy(this.dispatchCompleteData, (item) => {
          if (item.groupNo) {
            return item.groupNo
          }
          return 'all'
        })
        console.log('groupList', groupList)
        let rebuildData = []
        _.forIn(groupList, function (value, key) {
          if (key === 'all') {
            // rebuildData.push(value[0])
            value.forEach((item) => {
              item._disableExpand = true
              rebuildData.push(item)
            })
          } else {
            let singleData = {
              groupNo: key,
              shippingAddress: value[0].shippingAddress,
              expand: []
            }
            value.forEach((item) => {
              singleData.expand.push(item)
            })
            rebuildData.push(singleData)
          }
        })
        this.rebuildData = rebuildData
      },
      /**
       * TODO(选择当前行)
       * @auther zhangQ
       * @date 2018/4/3 16:49
       */
      onCurrentChange (currentRow, oldCurrentRow) {
        if (currentRow.groupNo) {
          this.currentRow = currentRow
          this.addDriverBtnDisabled = false
        } else {
          this.addDriverBtnDisabled = true
          this.currentRow = {}
        }
      },
      /**
       * TODO(追加司机)
       * @auther zhangQ
       * @date 2018/4/3 17:10
       */
      addDriver () {
        if (!this.currentRow.groupNo) {
          this.$Notice.warning({
            title: '警告',
            desc: '请点击要撤销的行'
          })
          return
        }
        this.currentRowDriversform = {
          driverIds: this.currentRow.expand[0].driverIds,
          address: this.currentRow.shippingAddress,
          contacts: this.currentRow.expand[0].contacts,
          cmobile: this.currentRow.expand[0].contactsMobile
        }
        this.operaModal.checkDriverShow = true
      },
      /**
       * TODO(保存追加的司机)
       * @auther zhangQ
       * @date 2018/4/4 11:05
       */
      addDriverSave (form) {
        // console.log('form', form)
        if (!(form.driverIds && form.driverIds.length > 0)) {
          this.$Message.error('司机必选')
          return
        }
        let param = {
          driverIds: JSON.stringify(form.driverIds),
          groupNo: this.currentRow.groupNo,
          mainOrderNo: this.currentMainOrder.orderNo
        }
        addDriverSave(param).then((res) => {
          if (+res.data.isSuccess === 1) {
            this.$Notice.success({
              title: '成功',
              desc: '追加成功'
            })
            this.currentRow.expand.forEach((item) => {
              item.driverIds = param.driverIds
            })
            console.log('this.currentRow', this.currentRow)
            this.operaModal.checkDriverShow = false
          } else {
            return Promise.reject(new Error(res.data.res))
          }
        }).catch(ex => {
          this.$Notice.warning({
            title: '失败',
            desc: ex
          })
        })
      }
    },
    mounted () {
      this.rebuildMethod()
      this.driverList.forEach((item) => {
        let py = pinyin.codefans_net_CC2PY(item.login_name)
        item.login_namePy = py
      })
    },
    components: { dispatchCompleteExpand, checkDriverModal, xlinkModal }
  }
</script>

<style scoped>

</style>
